<?php namespace App\Http\Services;

use App\Orders;
use App\OrderSyncLog;
use Requests_Exception;
use Requests;
use Log;
use \App\Http\Services\ToolsManager;

class SyncData
{
//    private $app_key    = '490a185338a436c394e192c6053adc58';//测试
    private $app_key    = '92c1f60fd2b3b62e5d172988559e7305';//正式
    private $app_secret = '127da71146a25580c3690ef7b89edad4';
    private $base_url   = 'https://mc3.sqzw.com/release/mc3/api/?app_act=webopen';

    protected $deal_code; //平台交易号
    protected $lylx="0"; //订单来源平台
    protected $sd_code="ht004"; //订单来源平台
    protected $user_name; //会员名称
    protected $pay_code; //支付代码
    protected $shipping_code; //快递方式代码
    protected $receiver_name; //收货人姓名
    protected $receiver_country="中国"; //收货人国家
    protected $receiver_province; //收货人省份
    protected $receiver_city; //收货人城市
    protected $receiver_district; //收货人的地区
    protected $receiver_addr; //收货人的详细地址
    protected $receiver_address; //收货人的详细地址
    protected $receiver_mobile; //收货人的手机号码
    protected $add_time; //订单下单时间
    protected $pay_time; //订单支付时间
    protected $pay_status; //付款状态
    protected $shipping_fee; //运费
    protected $order_amount; //应付金额
    protected $payment; //已付金额
    protected $is_cod=0;//交易类型 0:款到发货;1:货到付款
    protected $items;//子订单
    protected $order_sn; //MC3平台订单号

    /**
     * @return mixed
     */
    public function getDealCode()
    {
        return $this->deal_code;
    }

    /**
     * @param mixed $deal_code
     */
    public function setDealCode($deal_code)
    {
        $this->deal_code = $deal_code;
    }

    /**
     * @return string
     */
    public function getLylx()
    {
        return $this->lylx;
    }

    /**
     * @param string $lylx
     */
    public function setLylx($lylx)
    {
        $this->lylx = $lylx;
    }

    /**
     * @return string
     */
    public function getSdCode()
    {
        return $this->sd_code;
    }

    /**
     * @param string $sd_code
     */
    public function setSdCode($sd_code)
    {
        $this->sd_code = $sd_code;
    }

    /**
     * @return mixed
     */
    public function getUserName()
    {
        return $this->user_name;
    }

    /**
     * @param mixed $user_name
     */
    public function setUserName($user_name)
    {
        $this->user_name = $user_name;
    }

    /**
     * @return mixed
     */
    public function getPayCode()
    {
        return $this->pay_code;
    }

    /**
     * @param mixed $pay_code
     */
    public function setPayCode($pay_code)
    {
        $this->pay_code = $pay_code;
    }

    /**
     * @return mixed
     */
    public function getShippingCode()
    {
        return $this->shipping_code;
    }

    /**
     * @param mixed $shipping_code
     */
    public function setShippingCode($shipping_code)
    {
        $this->shipping_code = $shipping_code;
    }

    /**
     * @return mixed
     */
    public function getReceiverName()
    {
        return $this->receiver_name;
    }

    /**
     * @param mixed $receiver_name
     */
    public function setReceiverName($receiver_name)
    {
        $this->receiver_name = $receiver_name;
    }

    /**
     * @return string
     */
    public function getReceiverCountry()
    {
        return $this->receiver_country;
    }

    /**
     * @param string $receiver_country
     */
    public function setReceiverCountry($receiver_country)
    {
        $this->receiver_country = $receiver_country;
    }

    /**
     * @return mixed
     */
    public function getReceiverProvince()
    {
        return $this->receiver_province;
    }

    /**
     * @param mixed $receiver_province
     */
    public function setReceiverProvince($receiver_province)
    {
        $this->receiver_province = $receiver_province;
    }

    /**
     * @return mixed
     */
    public function getReceiverCity()
    {
        return $this->receiver_city;
    }

    /**
     * @param mixed $receiver_city
     */
    public function setReceiverCity($receiver_city)
    {
        $this->receiver_city = $receiver_city;
    }

    /**
     * @return mixed
     */
    public function getReceiverDistrict()
    {
        return $this->receiver_district;
    }

    /**
     * @param mixed $receiver_district
     */
    public function setReceiverDistrict($receiver_district)
    {
        $this->receiver_district = $receiver_district;
    }

    /**
     * @return mixed
     */
    public function getReceiverAddr()
    {
        return $this->receiver_addr;
    }

    /**
     * @param mixed $receiver_addr
     */
    public function setReceiverAddr($receiver_addr)
    {
        $this->receiver_addr = $receiver_addr;
    }

    /**
     * @return mixed
     */
    public function getReceiverAddress()
    {
        return $this->receiver_address;
    }

    /**
     * @param mixed $receiver_address
     */
    public function setReceiverAddress($receiver_address)
    {
        $this->receiver_address = $receiver_address;
    }

    /**
     * @return mixed
     */
    public function getReceiverMobile()
    {
        return $this->receiver_mobile;
    }

    /**
     * @param mixed $receiver_mobile
     */
    public function setReceiverMobile($receiver_mobile)
    {
        $this->receiver_mobile = $receiver_mobile;
    }

    /**
     * @return mixed
     */
    public function getAddTime()
    {
        return $this->add_time;
    }

    /**
     * @param mixed $add_time
     */
    public function setAddTime($add_time)
    {
        $this->add_time = $add_time;
    }

    /**
     * @return mixed
     */
    public function getPayTime()
    {
        return $this->pay_time;
    }

    /**
     * @param mixed $pay_time
     */
    public function setPayTime($pay_time)
    {
        $this->pay_time = $pay_time;
    }

    /**
     * @return mixed
     */
    public function getPayStatus()
    {
        return $this->pay_status;
    }

    /**
     * @param mixed $pay_status
     */
    public function setPayStatus($pay_status)
    {
        $this->pay_status = $pay_status;
    }

    /**
     * @return mixed
     */
    public function getShippingFee()
    {
        return $this->shipping_fee;
    }

    /**
     * @param mixed $shipping_fee
     */
    public function setShippingFee($shipping_fee)
    {
        $this->shipping_fee = $shipping_fee;
    }

    /**
     * @return mixed
     */
    public function getOrderAmount()
    {
        return $this->order_amount;
    }

    /**
     * @param mixed $order_amount
     */
    public function setOrderAmount($order_amount)
    {
        $this->order_amount = $order_amount;
    }

    /**
     * @return mixed
     */
    public function getPayment()
    {
        return $this->payment;
    }

    /**
     * @param mixed $payment
     */
    public function setPayment($payment)
    {
        $this->payment = $payment;
    }

    /**
     * @return mixed
     */
    public function getIsCod()
    {
        return $this->is_cod;
    }

    /**
     * @param mixed $is_cod
     */
    public function setIsCod($is_cod)
    {
        $this->is_cod = $is_cod;
    }

    /**
     * @return mixed
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @param mixed $items
     */
    public function setItems($items)
    {
        $this->items = $items;
    }

    public static function getGoodsList(){
        $data = [
            "pageNo"   => 1,
            "pageSize" => 20
        ];
        $apiName = "prm.goods.list_get";

        $resultData = null;
        $resultData = self::doRequest($apiName,$data);

        return $resultData;
    }

    //获取订单详情
    public static function getOrdersDetail($orderSn="",$deal_code=""){
        $data=[
            "orderSn"   => $orderSn,
            "deal_code" => $deal_code
        ];
        $apiName = "orm.order.detail_get";

        $resultData = null;
        $resultData = self::doRequest($apiName,$data);

        //同步日志
        $newLog = new OrderSyncLog();
        $newLog->order_id = $orderSn != "" ? $orderSn : $deal_code;
        $newLog->data_json = print_r($data,true);
        $newLog->type      = "get_order_detail";

        if($resultData && isset($resultData->status)){
            $newLog->status = $resultData->status;
        }
        if($resultData && isset($resultData->requestid)){
            $newLog->action = $resultData->requestid;
        }
        if($resultData && isset($resultData->message)){
            $newLog->remark = $resultData->message;
        }
        $newLog->save();

        return $resultData;
    }

    //添加订单接口
    public static function addOrders(SyncData $thatSyncData){
//        $thatSyncData = new SyncData();
        $data = [
            "deal_code"=>$thatSyncData->getDealCode(),
            "lylx"=>$thatSyncData->getLylx(),
            "sd_code"=>$thatSyncData->getSdCode(),
            "user_name"=>$thatSyncData->getUserName(),
            "pay_code" =>$thatSyncData->getPayCode(),
            "shipping_code"=>$thatSyncData->getShippingCode(),
            "receiver_name"=>$thatSyncData->getReceiverName(),
            "receiver_country"=>$thatSyncData->getReceiverCountry(),
            "receiver_province"=>$thatSyncData->getReceiverProvince(),
            "receiver_city"=>$thatSyncData->getReceiverCity(),
            "receiver_district"=>$thatSyncData->getReceiverDistrict(),
            "receiver_addr"=>$thatSyncData->getReceiverAddr(),
            "receiver_address"=>$thatSyncData->getReceiverAddress(),
            "receiver_mobile"=>$thatSyncData->getReceiverMobile(),
            "add_time"=>$thatSyncData->getAddTime(),
            "pay_time"=>$thatSyncData->getPayTime(),
            "pay_status"=>$thatSyncData->getPayStatus(),
            "shipping_fee"=>$thatSyncData->getShippingFee(),
            "order_amount"=>$thatSyncData->getOrderAmount(),
            "payment"=>$thatSyncData->getPayment(),
            "is_cod"=>$thatSyncData->getIsCod(),
            "items"=>$thatSyncData->getItems()
        ];

        $thatOrder = Orders::whereOrderNum($thatSyncData->getDealCode())->first();


        //同步日志
        $newLog = new OrderSyncLog();
        $newLog->order_id = $thatOrder ? $thatOrder->id : 0;
        $newLog->data_json = print_r($data,true);
        $newLog->type      = "add_order";
        $newLog->action    = "to_mc3";
        $newLog->save();

        $apiName = "orm.order.add";

        $resultData = null;
        $resultData = self::doRequest($apiName,$data);

        if($resultData && isset($resultData->status)){
            $newLog->status = $resultData->status;
        }

        if($resultData && isset($resultData->requestid)){
            $newLog->action = $resultData->requestid;
        }

        if($resultData && isset($resultData->message)){
            $newLog->remark = $resultData->message;
        }
        $newLog->save();

        return $resultData;
    }

    public static function updateOrders(SyncData $thatSyncData){
        $thatOrder = Orders::whereOrderNum($thatSyncData->getDealCode())->first();
        if(!$thatOrder || ($thatOrder && is_null($thatOrder->order_sn)))
            return false;

        $data = [
            "order_sn"=>$thatOrder->order_sn,
            "order_amount"=>$thatSyncData->getOrderAmount(),
            "payment"=>$thatSyncData->getPayment(),
            "items"=>$thatSyncData->getItems()
        ];

        //同步日志
        $newLog = new OrderSyncLog();
        $newLog->order_id = $thatOrder ? $thatOrder->id : 0;
        $newLog->data_json = print_r($data,true);
        $newLog->type      = "update_order";
        $newLog->action    = "to_mc3";
        $newLog->save();

        $apiName = "orm.order.update";

        $resultData = null;
        $resultData = self::doRequest($apiName,$data);

        if($resultData && isset($resultData->status)){
            $newLog->status = $resultData->status;
        }

        if($resultData && isset($resultData->requestid)){
            $newLog->action = $resultData->requestid;
        }

        if($resultData && isset($resultData->message)){
            $newLog->remark = $resultData->message;
        }
        $newLog->save();

        return $resultData;
    }

    public static function getGoodsStock($barCode = "",$page=1,$limit=20){
        $thatSyncData = new SyncData();
        $data = [
            "barcode" => $barCode,
            "pageNo"  => $page,
            "pageSize"=> $limit,
            "no_kc"   => 0,
            "kw_type" => 1
        ];

        $apiName = "stock.goods_sscx";

        $resultData = null;
        $resultData = self::doRequest($apiName,$data);

        return $resultData;
    }

    public static function doRequest($apiName = "",$data=[]){
        $thatSyncData = new SyncData();
        $signParam = [
            "method"      => $apiName,
            "format"      => "json",
            "key"         => $thatSyncData->app_key,
            "timestamp"   => date("Y-m-d H:i:s",time()),
            "v"           => "2.0",
            "sign_method" => "md5",
            "data"        => json_encode($data)
        ];

        $param = [
            "method"      => $apiName,
            "format"      => "json",
            "key"         => $thatSyncData->app_key,
            "timestamp"   => date("Y-m-d H:i:s",time()),
            "v"           => "2.0",
            "sign_method" => "md5",
            "sign"        => self::getSignKey($signParam),
            "data"        => json_encode($data)
        ];

        $response =null;
        try {
            $response = Requests::post($thatSyncData->base_url, [
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
            ], $param);
        } catch (Requests_Exception $ex) {
            Log::error('Request Error To YunPian:'.$ex);
        }

        if (!$response->success) {
            return false;
        }

        $res = json_decode($response->body);
        if (is_null($res))
            return false;

        return $res;
    }

    public static function getSignKey($param){
        $thatSyncData = new SyncData();
        $paramStr = ToolsManager::ASCII($param);
        $signMd5 = md5($thatSyncData->app_secret . $paramStr . $thatSyncData->app_secret);

        return strtoupper($signMd5);
    }

    private function doPost($url, array $param)
    {
        $response = null;
        try {
            $response = Requests::post($url, [
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
            ], $param);
        } catch (Requests_Exception $ex) {
            Log::error('Request Error To Sync:'.$ex);
        }

        if (!$response->success) {
            return false;
        }

        $res = json_decode($response->body);
        if (is_null($res))
            return false;

        return $res;
    }
}